<template>
  <div>
    <vxe-modal v-model="visible" esc-closable height="200" show-footer title="定时备份" width="490" @close="closeClick">
      <template #default>
        <vxe-form :data="taskForm" title-align="right" title-width="70">
          <vxe-form-item :item-render="{}" field="cycle" title="备份周期">
            <template #default>
              <vxe-select v-model="cron.cycle" style="width: 80px" transfer @change="cycleChange">
                <vxe-option
                  v-for="item in cycleList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item v-if="cron.cycle === 'yearly' && ok" :item-render="{}" field="month" title="">
            <template #default>
              <vxe-input v-model="cron.month" :max="12" :min="1" placeholder="" style="width: 80px" type="integer">
                <template #suffix>
                  <span>月</span>
                </template>
              </vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item v-if="cron.cycle === 'weekly' && ok" :item-render="{}" field="weekday" title="">
            <template #default>
              <vxe-select v-model="cron.weekday" style="width: 80px" transfer>
                <vxe-option
                  v-for="item in weeklyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item
            v-if="(cron.cycle === 'monthly' || cron.cycle === 'yearly') && ok"
            :item-render="{}"
            field="day"
            title=""
          >
            <template #default>
              <vxe-input v-model="cron.day" max="31" min="1" placeholder="" style="width: 80px" type="integer">
                <template #suffix>
                  <span>日</span>
                </template>
              </vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item :item-render="{}" field="time" title="">
            <template #default>
              <vxe-input v-model="cron.time" placeholder="时分秒" style="width: 100px" transfer type="time"></vxe-input>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
      <template #footer>
        <div style="text-align: center">
          <vxe-button v-if="taskForm.cron" content="删除" status="danger" @click="deleteTaskClick"></vxe-button>
          <vxe-button content="保存" status="primary" @click="taskSaveClick"></vxe-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
import { VXETable } from 'vxe-table/lib/v-x-e-table';
import { addTask, deleteTask, getTask } from '@bdp/sl/dataSecurity/api';

export default {
  components: {},
  name: 'TaskForm',
  data() {
    return {
      ok: true,
      visible: false,
      taskForm: {
        id: null,
        cron: null,
      },
      cycleList: [
        { label: '每日', value: 'daily' },
        { label: '每周', value: 'weekly' },
        { label: '每月', value: 'monthly' },
        { label: '每年', value: 'yearly' },
      ],
      weeklyList: [
        { label: '周一', value: '2' },
        { label: '周二', value: '3' },
        { label: '周三', value: '4' },
        { label: '周四', value: '5' },
        { label: '周五', value: '6' },
        { label: '周六', value: '7' },
        { label: '周日', value: '1' },
      ],
      cron: {
        cycle: 'daily',
        month: 1,
        weekday: '2',
        day: 1,
        time: '00:00:00',
      },
    };
  },
  created() {},
  methods: {
    init(row) {
      this.visible = true;
      this.$nextTick(() => {
        this.taskForm.id = row.id;
        this.getTask(row.id);
      });
    },
    // 获取定时任务
    getTask(id) {
      getTask(id)
        .then((res) => {
          if (res.data) {
            this.taskForm.cron = res.data.cron;
            this.parseCron();
          } else {
            this.reset();
          }
        })
        .catch(() => {});
    },
    // 重置字段
    reset() {
      this.taskForm.cron = null;
      this.cron = {
        cycle: 'daily',
        month: 1,
        weekday: '2',
        day: 1,
        time: '00:00:00',
      };
    },
    // 保存
    async taskSaveClick() {
      if (
        !this.cron.time ||
        (this.cron.cycle === 'weekly' && !this.cron.weekday) ||
        (this.cron.cycle === 'monthly' && !this.cron.day) ||
        (this.cron.cycle === 'yearly' && (!this.cron.day || !this.cron.month))
      ) {
        VXETable.modal.message({ content: '备份周期未填写完整', status: 'error' });
        return;
      }
      this.toCron();
      addTask(this.taskForm).then((res) => {
        if (res.code === 0) {
          VXETable.modal.message({ content: '保存成功', status: 'success' });
          this.closeClick();
        }
      });
    },
    // 删除任务
    async deleteTaskClick() {
      deleteTask(id).then((res) => {
        if (res.code === 0) {
          VXETable.modal.message({ content: '删除成功', status: 'success' });
          this.closeClick();
        }
      });
    },
    // 转cron表达式
    toCron() {
      const cycle = this.cron.cycle;
      const month = this.cron.month;
      const weekday = this.cron.weekday;
      const day = this.cron.day;
      const time = this.cron.time;
      const timeList = time.split(':');
      const hour = timeList[0];
      const minute = timeList[1];
      const second = timeList[2];

      switch (cycle) {
        case 'yearly':
          // 每年
          this.taskForm.cron = `${second} ${minute} ${hour} ${day} ${month} ?`;
          return;
        case 'monthly':
          // 每月
          this.taskForm.cron = `${second} ${minute} ${hour} ${day} * ?`;
          return;
        case 'weekly':
          this.taskForm.cron = `${second} ${minute} ${hour} ? * ${weekday}`;
          return;
        case 'daily':
          // 每日
          this.taskForm.cron = `${second} ${minute} ${hour} * * ?`;
          return;
        default:
          throw new Error('不支持的类型');
      }
    },
    // 解析cron表达式
    parseCron() {
      const parts = this.taskForm.cron.split(' ');
      if (parts.length !== 6 && parts.length !== 7) {
        return;
      }
      const [second, minute, hour, day, month, dayOfWeek, year] = parts;
      let cycle;
      if (month !== '*' && day !== '*' && dayOfWeek === '?') {
        cycle = 'yearly';
      } else if (month === '*' && day !== '*' && dayOfWeek === '?') {
        cycle = 'monthly';
      } else if (month === '*' && day === '?' && dayOfWeek !== '*') {
        cycle = 'weekly';
      } else if (month === '*' && day === '*' && dayOfWeek === '?') {
        cycle = 'daily';
      }

      this.cron = {
        cycle: cycle,
        month: cycle === 'daily' || cycle === 'monthly' || cycle === 'weekly' ? '' : month,
        day: cycle === 'daily' || cycle === 'weekly' ? '' : day,
        weekday: cycle === 'weekly' ? dayOfWeek : '',
        time: hour + ':' + minute + ':' + second,
      };
    },
    closeClick() {
      this.visible = false;
      this.$emit('close');
    },
    cycleChange() {
      this.ok = false;
      this.$nextTick(() => {
        this.ok = true;
      });
    },
  },
};
</script>
